﻿// Decompiled with JetBrains decompiler
// Type: MCM.Implementation.DropdownJsonConverter
// Assembly: MCMv5, Version=5.10.2.0, Culture=neutral, PublicKeyToken=null
// MVID: 7AB326B9-B2B4-41C2-9177-68E944071101
// Assembly location: D:\steam\steamapps\workshop\content\261550\2859238197\bin\Win64_Shipping_Client\MCMv5.dll

using BUTR.DependencyInjection.Logger;
using MCM.Abstractions;
using MCM.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

#nullable enable
namespace MCM.Implementation
{
  public sealed class DropdownJsonConverter : JsonConverter
  {
    private readonly IBUTRLogger _logger;
    private readonly Func<string, object?> _getSerializationProperty;

    public DropdownJsonConverter(IBUTRLogger logger, Func<string, object?> getSerializationProperty)
    {
      this._logger = logger;
      this._getSerializationProperty = getSerializationProperty;
    }

    public override bool CanConvert(Type objectType)
    {
      return SettingsUtils.IsForGenericDropdown(objectType);
    }

    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
      JToken.FromObject((object) new SelectedIndexWrapper(value).SelectedIndex).WriteTo(writer);
    }

    public override object? ReadJson(
      JsonReader reader,
      Type objectType,
      object? existingValue,
      JsonSerializer serializer)
    {
      try
      {
        if (existingValue == null)
          existingValue = this._getSerializationProperty(reader.Path);
        if (existingValue == null)
          return (object) null;
        SelectedIndexWrapper selectedIndexWrapper = new SelectedIndexWrapper(existingValue);
        JToken jtoken = JToken.Load(reader);
        int result;
        selectedIndexWrapper.SelectedIndex = int.TryParse(jtoken.ToString(), out result) ? result : selectedIndexWrapper.SelectedIndex;
      }
      catch (Exception ex)
      {
        this._logger.LogError(ex, "Error while deserializing Dropdown");
      }
      return existingValue;
    }
  }
}
